﻿
@{
    ViewBag.Title = "统一打包单页";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";

    var workshopCode = ViewBag.WorkshopCode as string;
    var packNo = ViewBag.PackNo as string;
    var user = ViewBag.User as IOA.MES.DataAccess.VModel.VUser;
}
@model IOA.MES.DataAccess.VModel.VPack

@section Contents{
    <style>
        .layui-form-label {
            width: auto;
        }

        .layui-table-cell {
            height: auto;
        }

        .grid-demo {
            line-height: 40px;
        }
    </style>
}

<div id="page"></div>

<script type="text/template" id="tplPage">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-form layui-card-header layuiadmin-card-header-auto">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">{{lang.Field.Duty}}：</label>
                        <div class="layui-input-inline">
                            @if (Model == null)
                            {
                                <select id="selDuties" name="DutyId" lay-filter="selDuties" @(Model != null ? "disabled" : "")>
                                    <option value="0">选择班次</option>
                                </select>
                            }
                            else
                            {
                                <input type="text" value="@Model.DutyName" disabled class="layui-input">
                            }
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">{{lang.Field.Machine}}：</label>
                        <div class="layui-input-inline">
                            @if (Model == null)
                            {
                                <select id="selMachines" name="MachineId" lay-filter="selMachines" @(Model != null ? "disabled" : "")>
                                    <option value="0">选择机台</option>
                                </select>
                            }
                            else
                            {
                                <input type="text" value="@Model.MachineName " disabled class="layui-input">
                            }
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">{{lang.Field.PackBatchNo}}：</label>
                        <div class="layui-input-inline">
                            <input type="text" name="PackBatchNo" placeholder="请输入包装批次号" autocomplete="off" class="layui-input" value="@(Model?.PackBatchNo )" @(Model != null ? "disabled" : "")>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">{{lang.Field.PackNo}}：</label>
                        <div class="layui-input-inline">
                            <input type="text" name="PackNo" placeholder="请输入包装编码" autocomplete="off" class="layui-input" value="@(Model==null?packNo:Model.PackNo)" @(Model != null ? "disabled" : "")>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <audio id="audioTip" src="/res/audio/success.mp3" style="display:none;"></audio>
                        <input type="hidden" name="PkId" value=" @(Model==null?0:Model.PkId)" />
                        @if (Model == null || Model.PkId <= 0)
                        {
                            <button class="layui-btn layui-btn-normal layuiadmin-btn-list" name="Pack" lay-filter="submit" lay-submit type="submit">{{lang.Field.CreatePack}}</button>
                        }
                        else if (Model.PackStatus == IOA.MES.DataAccess.Enum.PackStatus.Packing)
                        {
                            <button class="layui-btn layui-btn-normal layuiadmin-btn-list" name="FinishPack" lay-filter="submit" lay-submit type="submit">{{lang.Field.FinishPack}}</button>
                            <button class="layui-btn layui-btn-danger layuiadmin-btn-list" name="UnPack" lay-filter="submit" lay-submit type="submit">{{lang.Field.UnPack}}</button>
                        }
                        else if (Model.PackStatus == IOA.MES.DataAccess.Enum.PackStatus.Normal)
                        {
                            <button class="layui-btn layui-btn-normal layuiadmin-btn-list" name="PrintMark" lay-filter="submit" lay-submit type="submit">{{lang.Field.PrintMark}}</button>
                            if (Model.PackInspectStatus != IOA.MES.DataAccess.Enum.PackInboundInspectStatus.Inspected)
                            {
                                <button class="layui-btn layui-btn-danger layuiadmin-btn-list" name="UnPack" lay-filter="submit" lay-submit type="submit">{{lang.Field.UnPack}}</button>
                            }
                        }
                        else
                        {
                            <button class="layui-btn layui-btn-warm layuiadmin-btn-list" type="button">{{lang.Field.UnPacked}}</button>
                        }
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-card layui-form">
            <div class="layui-card-header">
                {{lang.Field.PackParams}}
            </div>
            <div class="layui-card-body packconditions">
                <div class="layui-row">
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="MaxSize" lay-filter="MaxSize" lay-skin="primary" title="打包数量" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="OrderNoLimit" lay-filter="OrderNoLimit" lay-skin="primary" title="订单号" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="WorkOrderNoLimit" lay-filter="WorkOrderNoLimit" lay-skin="primary" title="工单号" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="DataPlate" lay-filter="DataPlate" lay-skin="primary" title="铭牌型号" disabled>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="RatedPower" lay-filter="RatedPower" lay-skin="primary" title="额定功率" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="ElectricGrade" lay-filter="ElectricGrade" lay-skin="primary" title="电流档" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="CompGrade" lay-filter="CompGrade" lay-skin="primary" title="组件等级" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="CompColor" lay-filter="CompColor" lay-skin="primary" title="组件颜色" disabled>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="JunBoxSpecs" lay-filter="JunBoxSpecs" lay-skin="primary" title="接线盒规格" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="JunBoxFactory" lay-filter="JunBoxFactory" lay-skin="primary" title="接线盒厂家" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="BackPlanSpecs" lay-filter="BackPlanSpecs" lay-skin="primary" title="背板规格" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="BackPlanFactory" lay-filter="BackPlanFactory" lay-skin="primary" title="背板厂家" disabled>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="AluFrameSpecs" lay-filter="AluFrameSpecs" lay-skin="primary" title="铝框规格" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="AluFrameFactory" lay-filter="AluFrameFactory" lay-skin="primary" title="铝框厂家" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="BatterySpecs" lay-filter="BatterySpecs" lay-skin="primary" title="电池片规格" disabled>
                    </div>
                    <div class="layui-col-xs3">
                        <input type="checkbox" name="BatteryFactory" lay-filter="BatteryFactory" lay-skin="primary" title="电池片厂家" disabled>
                    </div>
                    <div class="layui-col-xs3">
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-card layui-form">
            <div class="layui-card-header">
                {{lang.Field.BasisForPackConsolidationRules}}
            </div>
            <div class="layui-card-body packconditions">
                <div class="layui-row">
                    <div class="layui-col-xs12">
                        <span id="spCondition"></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-body">
                <table id="table" lay-filter="table"></table>
            </div>
        </div>
    </div>
</script>


@section Scripts{
    <script>
        var workshopCode = '@workshopCode',
            barCode = '@ViewBag.BarCode';
        var packModel = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
        var curBarCodes = packModel == null ? new Array() : packModel.Products.map((obj) => { return obj.BarCode });

        var vm = new Vue({
            el: "#page",
            template: "#tplPage",
            data: {
                lang: JSON.parse(lang).package
            }
        });

        setTimeout(function () {
            initLayui();
        }, 50);
        function initLayui() {
            layui.use(['table', 'layer', 'form'], function () {
                var layer = layui.layer,
                    table = layui.table,
                    form = layui.form;

                queryDuties();
                queryMachines();
                function queryDuties() {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/Settings/QueryDuties",
                        data: {
                            page: 1,
                            limit: 0,
                            workshopCode: workshopCode,
                            status: 1
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                layer.msg(res.ErrMsg, { icon: 5 });
                                return;
                            }
                            $("#selDuties").html("");
                            var options = new Array();
                            for (var i = 0; i < res.Data.length; i++) {
                                options.push("<option value=\"" + res.Data[i].PkId + "\">" + res.Data[i].DutyName + "</option>");
                            }
                            $("#selDuties").html(options.join(""));
                            form.render();
                        }
                    });
                }
                function queryMachines() {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/Settings/QueryMachines",
                        data: {
                            page: 1,
                            limit: 0,
                            workshopCode: workshopCode,
                            lineId: 0,
                            status: 1,
                            machineType: 130
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                layer.msg(res.ErrMsg, { icon: 5 });
                                return;
                            }
                            $("#selMachines").html("");
                            var options = new Array();
                            for (var i = 0; i < res.Data.length; i++) {
                                options.push("<option value=\"" + res.Data[i].PkId + "\">" + res.Data[i].MachineName + "</option>");
                            }
                            $("#selMachines").html(options.join(""));
                            form.render();
                        }
                    });
                }

                $("input[name=PackNo]").focus();
                if ($("input[name=PackNo]").val().trim() === '') {
                    $("input[name=PackNo]").val(localStorage.getItem("lastPackNo"));
                } else if (packModel == null) {
                    localStorage.setItem("lastPackNo", $("input[name=PackNo]").val().trim());
                }
                $(document).on("keyup", "input[name=PackNo]", function () {
                    localStorage.setItem("lastPackNo", $(this).val());
                });
                form.on('submit(submit)', function (formData) {
                    if (formData.elem.name == "UnPack") {
                        layer.confirm('确定要解除打包吗？', { icon: 3, title: '提示' }, function (index) {
                            unPack();
                            layer.close(index);
                        });
                    } else if (formData.elem.name == "FinishPack") {
                        layer.confirm('确定要完成打包吗？完成打包后将自动申请入库', { icon: 3, title: '提示' }, function (index) {
                            finishPack(formData.field.PackNo);
                            layer.close(index);
                        });
                    } else {
                        var forms = formData.field;
                        console.log(forms);
                        if (forms.DutyId.trim() == "") {
                            layer.msg("请选择班次", { icon: 5 });
                            return;
                        } else if (forms.MachineId.trim() == "") {
                            layer.msg("请选择机台", { icon: 5 });
                            return;
                        } else if (forms.PackNo.trim() == "") {
                            layer.msg("请输入包装编号", { icon: 5 });
                            return;
                        }

                        forms.WorkshopCode = workshopCode;
                        pack(forms);
                    }
                });

                function pack(model) {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/WorkOrder/CreatePack",
                        data: {
                            model: model,
                            barCode: barCode
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        error: function () {
                            playAudio(false);
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                layer.msg(res.ErrMsg, { icon: 5 });
                                return;
                            }
                            window.parent.layui.layer.msg("包装创建成功！");

                            window.parent.postMessage({ type: 'new_pack', data: { pack: res.Data, barCode: barCode } }, '*')
                        }
                    });
                }
                function unPack() {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/WorkOrder/UnPack",
                        data: {
                            packNo: packModel.PackNo
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                layer.msg(res.ErrMsg, { icon: 5 });
                                return;
                            }
                            window.parent.layui.layer.msg("解除打包成功！");

                            window.parent.postMessage({ type: 'un_pack', data: { packNo: packModel.PackNo, packIndex: packModel.PackIndex } }, '*')
                        }
                    });
                }

                function finishPack() {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/WorkOrder/FinishPack",
                        data: {
                            packNo: packModel.PackNo
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                layer.msg(res.ErrMsg, { icon: 5 });
                                return;
                            }

                            window.parent.layui.layer.msg("打包完成！");
                            window.parent.postMessage({ type: 'finish_pack', data: { packNo: packModel.PackNo, packIndex: packModel.PackIndex } }, '*')
                        }
                    });
                }

                var options = {
                    elem: '#table'
                    , id: "table"
                    , limit: 1000
                    , cols: [[ //标题栏
                        { title: '序号', width: 80, type: "numbers" }
                        , { field: 'BarCode', title: '条码' }
                        , {
                            title: '状态', templet: function (d) {
                                return d.Status == '已打包' ? "<span style='color:green;'>" + d.Status + "</span>" : "<span style='color:red;white-space: pre-wrap;'>" + d.Status + "</span>";
                            }
                        }
                        , {
                            title: '操作', width: 200, templet: function (d) {
                                var str = '<button class="layui-btn layui-btn-sm layui-btn-danger delBarCode" code="' + d.BarCode + '"><i class="layui-icon">&#xe640;</i>删除</button>';
                                return str;
                            }
                        }
                    ]]
                    , data: packModel == null ? [] : packModel.Products
                    , limit: packModel == null ? 0 : packModel.Products.length
                    , even: true
                };
                if (packModel != null) {
                    renderPackCondition(packModel.PackCondition);
                    if (packModel.Products.length > 0) {
                        for (var i = 0; i < packModel.Products.length; i++) {
                            packModel.Products[i].Status = "已打包";
                        }
                    }
                }

                queryTable();
                function queryTable() {
                    if (table.index <= 0) {
                        table.render(options);
                    } else {
                        table.reload("table", options);
                    }
                }

                window.addEventListener('message', (res) => {
                    console.log(res);
                    if (res.data.type === 'pushCode') {
                        pushCode(res.data.data, "已打包");
                    }
                }, false);

                function renderPackCondition(condition) {
                    if (!condition) {
                        return;
                    }
                    $(".packconditions [type=checkbox]").each(function (e) {
                        for (var item in condition) {
                            if (item == $(this).attr("name")) {
                                if (item == "MaxSize") {
                                    $(this)[0].checked = condition[item] != null;
                                    $(this)[0].title = "打包数量" + (condition[item] != null ? ("：" + condition[item]) : "");
                                } else {
                                    $(this)[0].checked = condition[item];
                                }
                            }
                        }
                    });
                    $("#spCondition").text(condition.WorkOrderNo != "" ? ("工单配置：" + condition.WorkOrderNo) : ("订单配置：" + condition.OrderNo));

                    form.render("checkbox");
                }
                function pushCode(code, status) {
                    packModel.Products.splice(0, 0, { BarCode: code.toUpperCase(), Status: status });
                    if (packModel.Products.length === 1) {
                        location.reload();
                        return;
                    }
                    options.data = packModel.Products;
                    options.limit = packModel.Products.length;
                    table.reload("table", options);
                }

                $(document).on("click", ".delBarCode", function () {
                    var barCode = $(this).attr("code").trim().toUpperCase();
                    for (var i = 0; i < packModel.Products.length; i++) {
                        if (packModel.Products[i].BarCode == barCode) {
                            if (packModel.Products[i].Status != "已打包") {
                                var barCodeIndex = curBarCodes.indexOf(barCode);
                                if (barCodeIndex > -1) {
                                    curBarCodes.splice(barCodeIndex, 1);
                                }

                                packModel.Products.splice(i, 1);
                                options.data = packModel.Products;
                                options.limit = packModel.Products.length;
                                layui.table.reload("table", options);
                                return;
                            }
                            var loadId = layer.load();
                            $.ajax({
                                url: "/WorkOrder/UnPackProduct",
                                data: {
                                    barCode: barCode
                                },
                                complete: function () {
                                    layer.close(loadId);
                                },
                                success: function (res) {
                                    if (res.ErrCode != 200) {
                                        layer.msg(res.ErrMsg, { icon: 5 });
                                        return;
                                    }

                                    var barCodeIndex = curBarCodes.indexOf(barCode);
                                    if (barCodeIndex > -1) {
                                        curBarCodes.splice(barCodeIndex, 1);
                                    }

                                    packModel.Products.splice(i, 1);
                                    options.data = packModel.Products;
                                    options.limit = packModel.Products.length;
                                    layui.table.reload("table", options);
                                }
                            });
                            return;
                        }
                    }
                });
            });
        }
        function playAudio(success) {
            var dom = document.getElementById("audioTip");
            if (success) {
                dom.src="/res/audio/success.mp3";
            } else {
                dom.src = "/res/audio/error.mp3";
            }
            dom.currentTime = 0;
            dom.play();
        }
    </script>
}
